package com.dingding.manager.core.image;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.dingding.common.core.config.ImageUploadConfig;
import com.dingding.manager.core.util.ToolUtil;

import sun.misc.BASE64Decoder;

/**
 * @ClassName: ImageUpload
 * @Description: 图片上传
 * @author cheshaowei
 * @date 2015-11-16 下午05:57:32
 */
public class ImageUpload {

	private static final Logger log = Logger.getLogger(ImageUpload.class);

	/**
	 * 
	 * @Title: singleImageUpload @Description:用户头像上传 @param userAvatar
	 * 用户头像 @param newName 新图片名称 @param oldName 旧图片名称 @return String @author
	 * cheshaowei @throws
	 */
	public boolean userAvatarUpload(String userAvatar, String newName, String compressName, String oldName,
			String oldMiniName) {

		boolean isUploadSuccess = false;

		UploadUtil uploadUtil = new UploadUtil();

		// 删除旧头像 时间戳+“defaultAvatar.jpg”
		if (StringUtils.isNotBlank(oldName) && !oldName.endsWith("defaultAvatar.jpg")) {
			uploadUtil.deleteImage(oldName);
		}
		// 删除旧的压缩头像 时间戳+“defaultAvatar.jpg”
		if (StringUtils.isNotBlank(oldMiniName) && !oldMiniName.endsWith("defaultAvatar.jpg")) {
			uploadUtil.deleteImage(oldMiniName);
		}

		// base64解码
		byte[] data = baseConvert(userAvatar);

		// 上传新头像
		isUploadSuccess = uploadUtil.uploadImageToOss(data, newName);

		// 压缩头像
		byte[] compressData = compressImage(data);

		// 上传压缩头像
		isUploadSuccess = uploadUtil.uploadImageToOss(compressData, compressName);

		return isUploadSuccess;

	}

	/**
	 * @Title: driverAuthUpload @Description:车主认证图片上传 车主重新认证不删除旧图片，仍保留 @author
	 * cheshaowei @throws
	 */
	public boolean driverAuthUpload(List<String> listData, List<String> listName) {

		UploadUtil uploadUtil = new UploadUtil();

		for (int i = 0; i < listData.size(); i++) {
			String imageData = listData.get(i);
			String imageName = listName.get(i);
			// base64解码
			byte[] data = baseConvert(imageData);
			boolean isSuccess = uploadUtil.uploadImageToOss(data, imageName);
			if (!isSuccess) {
				log.error("图片上传出现异常！");
				return false;
			}
		}

		return true;
	}
	
	/**
	 * 
	 * 拼接图片访问名称
	 * 
	 * 说明：2016-05-25 修改(CHEHUANBO)
	 * 
	 * @param name 图片名称
	 * @author CHEHUANBO
	 * @return String 拼接后的图片访问地址
	 * 
	 */
	public static String imageAddress(String name) {

		StringBuffer str = new StringBuffer(ImageUploadConfig.getIMAGE_ACCESS_PATH());
		str.append(name);

		return str.toString();
	}
	

	/**
	 * 压缩图片
	 * 
	 * @param compressData
	 *            待压缩的二进制图片数据
	 * @author chehuanbo
	 * @return
	 */
	private byte[] compressImage(byte[] compressData) {

		InputStream content = null;
		ByteArrayOutputStream bos = null;
		ImageOutputStream ios = null;
		try {
			// 获取指定文件的输入流
			content = new ByteArrayInputStream(compressData);
			// 将图片字节流加载到内存中
			BufferedImage bufferedImage = ImageIO.read(content);
			// 压缩计算 0.3倍压缩
			float resizeTimes = 0.3f;
			// 原始图像的宽度和高度
			int width = bufferedImage.getWidth();
			int height = bufferedImage.getHeight();

			// 调整后的图片的宽度和高度
			int toWidth = (int) (width * resizeTimes);
			int toHeight = (int) (height * resizeTimes);
			BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
			// 执行压缩
			result.getGraphics().drawImage(
					bufferedImage.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);

			bos = new ByteArrayOutputStream();// 存储图片文件byte数组
			ios = ImageIO.createImageOutputStream(bos);
			ImageIO.write(result, "jpg", ios); // 图片写入到 ImageOutputStream

			return bos.toByteArray();

		} catch (IOException e) {
			log.error("压缩图片发生异常!", e);
			return null;
		} finally {

			if (content != null) {
				try {
					content.close();
				} catch (IOException e) {
					log.error("关闭流出现异常！", e);
				}
			}

			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					log.error("关闭流出现异常！", e);
				}
			}

			if (ios != null) {
				try {
					ios.close();
				} catch (IOException e) {
					log.error("关闭流出现异常！", e);
				}
			}

		}

	}

	/**
	 * @Title: baseConvert @Description:将base64字符串转换成byte字节 @author
	 * cheshaowei @throws
	 */
	private static byte[] baseConvert(String uploadData) {

		// Base64解码
		byte[] data = null;
		try {
			BASE64Decoder decoder = new BASE64Decoder();
			data = decoder.decodeBuffer(uploadData);
			for (int i = 0; i < data.length; ++i) {
				if (data[i] < 0) {// 调整异常数据
					data[i] += 256;
				}
			}
		} catch (IOException e) {
			log.error("将base64字符串转换成byte字节出现异常！", e);
		}
		return data;
	}

	/**
	 * @Description:上传到oss图片文件
	 * @param base64Code
	 *            base64编码的图片文件
	 * @author fengshuonan
	 * @return String 图片的文件名称,图片的名称为时间戳随机数（例如：xxx.jpg）
	 * @since 2.4
	 */
	public String upLoadPicture(String base64Code) {
		//生成文件名
		String fileName = ToolUtil.getRandomNum() + ".jpg";
		//上传base64编码的图片到云服务器
		UploadUtil uploadUtil = new UploadUtil();
		byte[] data = baseConvert(base64Code);
		
		boolean isSuccess = uploadUtil.uploadImageToOss(data, fileName);
		
		if(isSuccess){
			return fileName;
		}else{
			log.error("上传图片到OSS中时，出错错误！ImageUpload:upLoadPicture()");
			return "";
		}
	}
	
	/**
	 * @Description:上传到oss图片文件
	 * @param base64Str 包含base字符串的base64图片字符串
	 * @author hufan
	 * @return String 图片的文件名称,图片的名称为时间戳随机数（例如：xxx.jpg）
	 * @since 2.5.7
	 */
	public String uploadWebPicture(String base64Str) {
		
		if (StringUtils.isBlank(base64Str)) {
			log.error("图片字符串为空！ImageUpload:upLoadPicture()");
			return "";
		}
		String baseNew = base64Str.replaceAll(" ", "+");
		// 生成文件名
		String fileName = ToolUtil.getRandomNum() + ".jpg";
		// 上传base64编码的图片到云服务器
		UploadUtil uploadUtil = new UploadUtil();

		// 特殊处理：截取base64字符串
		byte[] data = baseConvert(baseNew.substring(baseNew.indexOf(",")+1));

		boolean isSuccess = uploadUtil.uploadImageToOss(data, fileName);

		if (isSuccess) {
			return fileName;
		} else {
			log.error("上传图片到OSS中时，出错错误！ImageUpload:upLoadPicture()");
			return "";
		}
	}
}
